<!-- 预打包管理 - 库存分配 -->
<template>
  <div style="padding: 15px;">
    <el-form ref="form" :model="form" label-width="100px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="预打包单号">
              <el-input v-model="form.code" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="仓库" >
              <el-input v-model="form.warehouseName" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商">
              <el-input v-model="form.shipmentName" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="包裹数">
              <el-input v-model="form.packageQuantity" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="grid-content bg-purple">
            <el-form-item  label="备注">
              <el-input v-model="form.remarks" style="width:88%" :disabled="true"  />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      resizable
      show-overflow
      ref="xTable"
      :edit-rules="validRules"
      :align="allAlign"
      :data="tableData"
      show-footer
      :span-method="objectSpanMethod"
      :footer-method="footerMethod"
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <!-- <vxe-table-column field="receiveCode" title="" width="0" ></vxe-table-column> -->
      <vxe-table-column field="goodsName" title="商品名称" width="270"></vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位" width="120"></vxe-table-column>
      <vxe-table-column field="combinationQuantity" title="数量"  width="120"></vxe-table-column>
      <vxe-table-column field="totalQuantity" title="总数量"  width="120"></vxe-table-column>
      <vxe-table-column field="notDistributionQuantity" title="剩余数量" width="120" v-if="type === 1"></vxe-table-column>
      <vxe-table-column field="distributionQuantity" title="分配数量" width="120"></vxe-table-column>
      <vxe-table-column field="locationName" title="分配库位"  width="120" ></vxe-table-column>
      <vxe-table-column field="cancelQuantity" title="取消数量" width="120" :edit-render="{name: 'input'}" v-if="type === 0"></vxe-table-column>
      <vxe-table-column field="goodsStatusName" title="库存状态" width="120"></vxe-table-column>
      <vxe-table-column field="containerBarCode" title="容器号" width="120" v-if="type === 0"></vxe-table-column>
      <vxe-table-column field="gmtManufacture" title="生产日期" width="120"></vxe-table-column>
      <vxe-table-column field="gmtExpire" title="过期日期" width="120" v-if="type === 0"></vxe-table-column>
      <vxe-table-column field="receiveLot" title="收货批次" width="120" v-if="type === 0"></vxe-table-column>
      <vxe-table-column field="remarks" title="备注"  v-if="type === 1" width="120"></vxe-table-column>
      <vxe-table-column title="操作" fixed="right" width="200" v-if="type === 1">
        <template slot-scope="scope">
          <el-button type="text" @click="inventoryFunc(scope.row.prepackagedItemCode)" v-if="scope.row.totalDistributionQuantity < scope.row.totalQuantity" :disabled="inventoryShow">
            库存分配
          </el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div class="allocationBut" v-if="type === 1">
      <el-button type="primary" :loading="autoDistriLoad" :disabled="autoDistriDis" plain @click="autoDistribute">自动分配</el-button>
      <el-button type="primary" :loading="pickingLoads" :disabled="pickingDis" plain @click="picking">生成拣货单</el-button>
    </div>
    <div class="allocationBut" v-if="type === 0">
      <el-button type="primary" :loading="autoDistriLoad" plain @click="unassign">确定</el-button>
    </div>
    <vxe-modal v-model="modelEditFlag" title="库存分配" width="780" height="600" resize  destroy-on-close>
      <compEdit :codeRef="codeRef" @fatherEditMethod="fatherEdit" />
    </vxe-modal>
    <!-- <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmitCheck" plain>确 认</el-button>
    </div> -->
  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'
  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
  import compEdit from './inventoryItem.vue'
  import { prepackagedDetail, autoDistribute, picking, prepackagedCancel } from '@/api/packManagement/prePackaged'
  export default {
    name: 'toPackedDetail',
    components: {
      compEdit
     },
    data() {
      return {
        type: '',
        allAlign:'center',
        spanArr: [], // 一个空的数组，用于存放每一行记录的合并数
        pos: 0, // spanArr 的索引
        contentSpanArr: [],
        position: 0,
        form: {},
        loading: false,
        tableData: [],
        listQuery: {
          page: 1,
          limit: 13,
          totalzong: 0
        },
        modelEditFlag: false,
        codeRef: '',
        validRules: {
          distributionQuantity: [
            { required: true, message: '分配数量必须填写' },
            { pattern: /^[1-9]+[0-9]*$/, message: '分配数量必须大于0' }
          ],
        },
        autoDistriLoad: false,
        pickingLoads: false,
        autoDistriDis: false,
        pickingDis: false,
        inventoryShow: false
      }
    },
    created() {
      this.getInfo()
      this.type = this.$route.query.type
    },
    mounted(){
      if(this.type === 1){
        this.modifyTitle('inventoryAllocation', '库存分配')
      }else{
        this.modifyTitle('inventoryAllocation', '取消分配')
      }
    },
    methods: {
      // 获取页面信息
      getInfo() {
        this.loading = true
        let code = this.$route.query.code ? this.$route.query.code : "";
        prepackagedDetail(code).then(response => {
          this.form = response.data
          this.tableData = this.form.prepackagedItemWithDistributionVOList
          const exportData = []
          this.tableData.forEach((item, index)=>{
            const flag = `${item.goodCode}${item.goodsName}${item.goodsBarCode}${item.goodsUnitName}`
            if (exportData.length === 0) {
              item.flag = flag
              // 可用数量
              exportData.push(item)
            } else {
              const result = exportData.filter(currentItem => currentItem.flag === flag)

              if (result.length === 0) {
                item.flag = flag
                exportData.push(item)
              } else {
                let idx = exportData.indexOf(result[0])
                exportData.splice(idx+1, 0, item)
              }
            }
          })
          this.tableData = exportData
          this.spanArr = [];
          this.contentSpanArr = [];
          for (var i = 0; i < this.tableData.length; i++) {
            if (i === 0) {
              this.spanArr.push(1);
              this.pos = 0;
              this.contentSpanArr.push(1);
              this.position = 0;
            } else {
              // 判断当前元素与上一个元素是否相同(第1和第2列)
              if (this.tableData[i].goodCode == this.tableData[i - 1].goodCode &&
                this.tableData[i].goodsName == this.tableData[i - 1].goodsName &&
                this.tableData[i].goodsBarCode == this.tableData[i - 1].goodsBarCode &&
                this.tableData[i].goodsUnitName == this.tableData[i - 1].goodsUnitName
              ) {
                this.spanArr[this.pos] += 1;
                this.spanArr.push(0);
              } else {
                this.spanArr.push(1);
                this.pos = i;
              }
            }
          }
          this.loading = false
        })
      },
      // 返回
      // funcSubmitCheck() {
      //   this.$router.push({
      //     path: "/pack/toPacked"
      //   });
      // },
      // 自动分配
      autoDistribute(){
        this.autoDistriLoad = true
        this.pickingDis = true
        this.inventoryShow = true
        let code = this.$route.query.code ? this.$route.query.code : "";
        autoDistribute(code).then(response => {
          this.$message({ message: response.msg, type: 'success' })
          this.getInfo()
          this.$eventBus.$emit('refreshList')
          // this.$store.dispatch("tagsView/delView", this.$route);
          // this.$router.push({
          //   path: '/pack/prePackaged'
          // })
        }).finally(() => {
          this.autoDistriLoad = false
          this.pickingDis = false
          this.inventoryShow = false
        })
      },
      // 生成拣货单
      picking() {
        this.pickingLoads = true
        this.autoDistriDis = true
        this.inventoryShow = true
        let code = this.$route.query.code ? this.$route.query.code : "";
        picking(code).then(response => {
          this.$message({ message: response.msg, type: 'success' })
          this.getInfo()
        }).finally(() => {
          this.pickingLoads = false
          this.autoDistriDis = false
          this.inventoryShow = false
        })
      },
      // 库存分配 弹窗
      inventoryFunc(code) {
        this.codeRef = code
        this.modelEditFlag = !this.modelEditFlag
      },
      // 库存分配 返回
      fatherEdit() {
        this.modelEditFlag = !this.modelEditFlag
        this.getInfo()
      },
      // 取消分配
      unassign() {
        this.form.deliveryItemWithDistributionVOList = this.$refs.xTable.tableData
        const data = this.form
        let a = ''
        this.$refs.xTable.validate((errMap) => {
          if (errMap) {
            this.form.deliveryItemWithDistributionVOList.forEach( i => {
              if(i.cancelQuantity == '' || i.cancelQuantity == undefined){
                i.cancelQuantity = 0
              }
            })
            let array = this.form.deliveryItemWithDistributionVOList
            for (let i = 0; i < array.length; i++) {
              if(array[i].cancelQuantity > array[i].distributionQuantity || array[i].cancelQuantity < 0){
                this.$message.error('取消数量不可大于分配数量且为非负整数')
                a =1
                break;
              }else a = 0
            }
            if(a == 0){
              this.isDisable = true
              prepackagedCancel(data).then(response => {
                this.$message({ message: response.msg, type: 'success' })
                this.$eventBus.$emit('refreshList')
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push({
                  path: '/pack/prePackaged'
                })
              })
            }
          } else {
            this.$XModal.message({ status: 'error', message: '校验不通过！' })
            return false
          }
        })
      },
      // 表格合并行
      objectSpanMethod({ row, rowIndex,column,  columnIndex }) {
        if(this.type === 1) {
          if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 || columnIndex === 6 || columnIndex === 7) {
            const _row = this.spanArr[rowIndex];
            const _col = _row > 0 ? 1 : 0;
            return {
              rowspan: _row,
              colspan: _col
            };
          }
        } else if(this.type === 0) {
          if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 || columnIndex === 6) {
            const _row = this.spanArr[rowIndex];
            const _col = _row > 0 ? 1 : 0;
            return {
              rowspan: _row,
              colspan: _col
            };
          }
        }

      },
      footerMethod ({ columns, data }) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 1) {
              return '合计'
            }
            if (['distributionQuantity'].includes(column.property)) {
              return parseFloat(XEUtils.sum(data, column.property).toFixed(6))
            }
            if (['totalQuantity'].includes(column.property)) {
              return this.form.totalQuantity
            }
            if (['notDistributionQuantity'].includes(column.property)) {
              return this.form.totalNotDistributionQuantity
            }
            return '-'
          })
        ]
      }
    }
  }
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 150px auto;
    width: 200px;
    // float: right;
  }
</style>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }
  .vxe-toolbar{padding:0 0 10px 0}
  .allocationBut{
    width: 350px;
    margin: 50px auto 0;
    padding-right: 40px;
  }
</style>
